//
//  ZSUDPClient.m
//  ZhuShou
//
//  Created by Dejun Liu on 15/11/9.
//  Copyright © 2015年 jw. All rights reserved.
//

#import "ZSUDPClient.h"

@implementation ZSUDPClient

- (void)sendString:(NSString *)string
          hostIP:(NSString *) ip
            port:(UInt16) port
         timeout:(NSTimeInterval) timeout
             tag:(long) tag
{
    [self sendData:[string dataUsingEncoding:NSUTF8StringEncoding] hostIP:ip port:port timeout:timeout tag:tag];
}

- (void)sendData:(NSData *)data
          hostIP:(NSString *) ip
            port:(UInt16) port
         timeout:(NSTimeInterval) timeout
             tag:(long) tag
{
    //client
    _client = [[GCDAsyncUdpSocket alloc]initWithDelegate:self delegateQueue:dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)];
    [_client sendData:data toHost:ip port:port withTimeout:timeout tag:tag];
    NSError *error;
    [_client beginReceiving:&error];
}

#pragma mark AsyncUdpSocketDelegate

- (void)udpSocket:(GCDAsyncUdpSocket *)sock didConnectToAddress:(NSData *)address
{
    DLog(@"didConnectToAddress");
}

- (void)udpSocket:(GCDAsyncUdpSocket *)sock didNotConnect:(NSError *)error
{
    DLog(@"didNotConnect");
}

- (void)udpSocket:(GCDAsyncUdpSocket *)sock didSendDataWithTag:(long)tag
{
    DLog(@"didSendDataWithTag:%@,%d",sock.connectedHost,sock.localPort);
}

- (void)udpSocket:(GCDAsyncUdpSocket *)sock didNotSendDataWithTag:(long)tag dueToError:(NSError *)error
{
    DLog(@"didNotSendDataWithTag");
}

- (void)udpSocket:(GCDAsyncUdpSocket *)sock didReceiveData:(NSData *)data
      fromAddress:(NSData *)address
withFilterContext:(id)filterContext
{
    DLog(@"didReceiveData:%@",[data stringUTF8]);
}

- (void)udpSocketDidClose:(GCDAsyncUdpSocket *)sock withError:(NSError *)error
{
    DLog(@"udpSocketDidClose");
}

@end
